package com.king.im.server;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.king.common.lang.Consts;
import com.king.im.handler.IMMsgHandlerFactory;
import com.king.im.handler.IMMsgHanlder;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.Map;

@Slf4j
public class IMWsMsgHanlder implements IWsMsgHandler {

    /**
     * 握手
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        /*return null;//不支持握手*/

        // 绑定个人通道
        String userId = httpRequest.getParam("userId");
        Tio.bindUser(channelContext,userId);
        log.info("{} ---------> 正在握手！"+userId);
        return httpResponse;
    }

    /**
     * 握手完成之后
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @throws Exception
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

        // 绑定群聊通道，群名：e-group-study
        Tio.bindGroup(channelContext, Consts.IM_DEFAULT_GROUP_NAME);
        log.info("{} ---------> 已绑定群【"+Consts.IM_DEFAULT_GROUP_NAME+"】！"+channelContext.getId());
    }

    /**
     * 接收字节类型消息
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    /**
     * 当关闭连接时
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    /**
     * 接收字符类型消息
     * @param wsRequest
     * @param s type,data
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {

        log.info("接收到消息 ------------> {}",s);

        Map map = JSONUtil.toBean(s, Map.class);
        String type = MapUtil.getStr(map,"type");
        String data = MapUtil.getStr(map,"data");

        IMMsgHanlder msgHandler = IMMsgHandlerFactory.getMsgHandler(type);
        msgHandler.handle(data,wsRequest,channelContext);//处理消息

        return null;
    }
}
